<?php
/**
 * 《传真管理》实现类
 *
 * @author 孙晓晔
 * @version $Id: LogAction.class.php 1035 2010-03-26 05:24:59Z sunxy $
 */

require_once(dirname(__FILE__) . '/FaxUtil.class.php');

class Fax extends FaxUtil {
	
	public $call = array(
		'-' => '请选择',
		'1' => '电信线路',
		'2' => '网络电话',
		'3' => '内部电话',
	);

	public $groupby = array(
		'-' => '请选择',
		'ip' => 'IP',
		'mac' => 'MAC',
		'2' => '日期',
		'3' => '月份',
	);

	public $orderby = array(
		'-' => '请选择',
		'ip' => 'IP',
		'mac' => 'MAC',
		'1' => '创建时间',
		'2' => '更新时间',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/03/06 11:29:07 $';
		$request['revision'] = '$Revision: 1.2 $';

		parent::__construct($request);
	}
	
	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('call_option', $this->call);
	}
	
	function _call_number($s) {
		if (preg_match("/^(2|6|8)\d{3}$/i", $s)) {
			return '3';
		}
		
		if (preg_match("/^(\+|00)/i", $s)) {
			return '2';
		}
		
		return '1';
	}
	
	function tab($controller, $request) {		
		$data = array(
			'发送传真' => array('cc'=>'fax.php?do=Fax.add', 'js'=>''),
			'传真信息' => array('cc'=>'fax.php?do=Fax.find', 'js'=>''),
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tab');
		return true;
	}
	
	function layout($controller, $request) {
		$this->pretreat($controller);
			
		// $controller->assign('t1', strtotime('-1 week'));
		// $controller->assign('t2', strtotime('+1 day'));
		
		require_once 'IMAP.connection_wizard.php'; 
		// Attempt to find the correct URI for any protocol based on common 
		// port settings and configurations 
		
		if (FALSE != ($url = Mail_IMAP_connection_wizard('mail.tecmold.com', 'sunxy@tecmold.com', 'jeaf', 'imap'))) { 
			echo $uri; 
		} else { 
			echo 'A suitable URI could not be detected.'; 
		}
		 
		// Attempt to find the correct URI on a specific protocol and port setting // 
		// Mail_IMAP_connection_wizard('mail.yourserver.net', 'mailuser', 'mailpass', 'imap', 143);
		

		$controller->display($request, 'mail/layout');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);
			
		// $controller->assign('t1', strtotime('-1 week'));
		// $controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'log/arp/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == '`join`') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['join'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$mac_s = $request['mac_s'];
		$ip_s = $request['ip_s'];

		$where = " WHERE 1=1";
		if (!empty($mac_s)) {
			$where .= " AND mac = '" . $mac_s . "'";
		}

		if (!empty($ip_s)) {
			$where .= " AND ip like '" . $ip_s . "%'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);
		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {
			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'log/arp/list');
		return true;
	}
	
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'fax/add');
		return true;
	}
	
	function send($controller, $request) {
		$this->pretreat($controller);
		
		$s = $request['number'];
		$call = $this->_call_number($s);
		
		$controller->assign_by_ref('call', $call);

		$controller->display($request, 'fax/send');
		return true;
	}
	
	function ajax_upload($controller, $request) {
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}

		$to = $request['to'];

		if ($file->isValid()) {
			$filename = $file->upload['tmp_name'];
			$name = $file->upload['name'];
			debug(print_r($file->upload, true));

			if ($this->_ftp($filename, $name)) {	
				$url = "http://ns11.tecmold.netfax.php?do=Fax.ajax_sendfax&to=" . $to . "&filename=" . urlencode($name);
				debug($url);
				file_get_contents($url);
			}
		}

		echo "1";
		return true;
	}
	
	function _ftp($src, $dst) {
		$host = '192.168.16.11';
		$user = 'tt';
		$pass = 'jeaf';
		
		$conn = ftp_connect($host) or die("Couldn't connect to $host");
		$result = ftp_login($conn, $user, $pass);
		if (!$conn || !$result) {
			echo "FTP connection has failed!";
			return false;
		}
		 
		$upload = ftp_put($conn, $dst, $src, FTP_BINARY) or die("Couldn't connect to $host");
		ftp_quit($conn);
		
		if (!$upload) {
			return false;
		}
		
		ftp_close($conn);

		return true;
	}
	
	function ajax_sendfax($controller, $request) {

		$to = $request['to'];
		
		$dir = "/home/ftp/tecmold.com/ftp/tt/";
		$filename = $request['filename'];
		
		$cmd = sprintf("sendfax -h %s -n -d %s %s%s", 'ttyIAX2@127.0.0.1', $to, $dir, $filename);
		// $cmd = sprintf("sendfax -n -d %s '%s%s'", $to, $dir, $filename);
		debug($cmd);
		exec($cmd);

		echo "1";
		return true;
	}
		
	function addPost($controller, $request) {

		$this->_add($request);
		
		$this->findPost($controller, $request);
		return true;
	}
	
	function _add($request) {
		require_once(dirname(__FILE__) . '/../emp/Mac.class.php');
		$aa = new Mac();
				
		return $aa->_add($request); 
	}
	
	function view($controller, $request) {
		$this->pretreat($controller);

		$row = $this->_view($request['id']);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'log/arp/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row = $this->_view_t($row);
		
		$row['mac_x'] = $this->_emp_mac($row['mac']);
		
		$row['ip_x'] = $this->_emp_ip($row['ip']);

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-7 day'));
		$controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'log/action/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'ip') {
			$row['a'] = $this->name_ip($row['a']);
		} else {
			$row = $this->_name_t($row, $px);
		}

		return $row;
	}
	
	function t($controller, $request) {

		$dsn = "sqlite:////home/sunxy/db/fax.db";

		try{
			$pdo = new PDO($dsn);
		}
		catch (PDOException $e){
			die ($e->getMessage());
		}

		foreach ($pdo->query('SELECT id FROM info_fax_recvq limit 10;') as $row)
		{
			echo $row[0] . "\n";
		}

		// $pdo = new PDO("sqlite:mydb.sqlite");
		
		// 準備新增資料的語法
		$sql = "INSERT INTO 'address_book'('name', 'phone', 'address' ) VALUES( :name, :phone, :address)";
		$pdoStatement = $pdo->prepare($sql);
		// 塞入資料並執行
		$aa = array(
        	':name' => 'shinder',
            ':phone' => '0918981520',
            ':address' => '新北市中和區'
		);
		$count = $pdoStatement->execute($aa);
		
		echo 'Insert Count: ' . $count . '<br>';
		$sid = $pdo->lastInsertId();
		echo 'lastInsertId: ' . $sid . '<br>';
		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}	
	
	function z($controller, $request) {
		$dir = "/home/sunxy/Desktop/z/";
		$dir = "/home/file/财务";
		// $dir = "/home/sunxy/abc";
		$this->_dir($dir);

		logdate($controller, $request);
		return true;
	}
	
	var $count = 0;
	function _dir($dir) {
		
		$dh = opendir($dir);
		while (($name = readdir($dh)) !== false) {
			if ($name == '.' || $name == '..') {
				continue;
			}

			$fmt = "%s/%s";
			$file = sprintf($fmt, $dir, $name);
			if (is_dir($file)) {
				$this->_dir($file);
			} else {				
				if ($this->_file($file, $name)) {
					echo sprintf("%s deleted\n", $file);					
					// echo "S";
				} else {
					echo ".";
				}
				
				$this->count++;
			}
			
			if (($this->count % 1000) == 0) {
				echo sprintf("\n%s\n", $this->count);
			}
		}

		closedir($dh);
	}
	
	function _file($file, $name) {
		$a = lstat($file);
		// print_r($a);
				
		$tbl = "test.file";
		
		$db = newdb("test");
		$fmt = "SELECT * FROM %s WHERE name = '%s' AND size = '%s' AND mtime = '%s'";
		$sql = sprintf($fmt, $tbl, $name, $a['size'], $a['mtime']);
		// echo $sql . "\n";
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			if ($row['file'] == $file) {
				return false;
			}
			
			echo sprintf("'%s' '%s'\n", $row['file'], $file);
			
			unlink($file);
			$cmd = sprintf("ln -s '%s' '%s'", $row['file'], $file);
			exec($cmd);
					
			return true;
		}
		
		$fmt = "INSERT INTO %s(file, name, size, mtime) VALUES('%s', '%s', '%s', '%s')";
		$sql = sprintf($fmt, $tbl, $file, $name, $a['size'], $a['mtime']);
		// echo $sql . "\n";
		$db->query($sql);
		
		return false;
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email($request['a']);
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			// echo "222";
			return false;
		}

		$from = $this->email;
		$subject = $request['title'];
		$ip = $request['ip'];
		
		$cc = array(	
			'新增信息'=>array('w' => "ip LIKE '$ip' AND DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'id DESC'),
			// '更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'id DESC'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}

		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'log/arp/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
}
?>
